﻿Shader "Custom/SnowShader" {
	Properties {
    	_MainTex ("Base (RGB)", 2D) = "white" {}
    	_Bump ("Bump", 2D) = "bump" {}
    	_Snow ("Snow Level", Range(0,1) ) = 0.5
    	_SnowColor ("Snow Color", Color) = (1.0,1.0,1.0,1.0)
    	_SnowDirection ("Snow Direction", Vector) = (0,1,0)
		_SnowDepth ("Snow Depth", Range(0,0.3)) = 0.1

	}
	SubShader {
		Tags { "RenderType"="Opaque" }
		//Tags { "RenderType"="Transparent" }
		//Tags { "Queue"="Transparent" }
		LOD 200
		
		CGPROGRAM
		// Physically based Standard lighting model, and enable shadows on all light types
		//#pragma surface surf Standard fullforwardshadows
		#pragma surface surf CustomDiffuse vertex:vert

		// Use shader model 3.0 target, to get nicer looking lighting
		#pragma target 3.0
		inline float4 LightingCustomDiffuse (SurfaceOutput s, fixed3 lightDir, fixed atten) {
    		float difLight = max(0, dot (s.Normal, lightDir));
    		float4 col;
    		col.rgb = s.Albedo * _LightColor0.rgb * (difLight * atten * 2);
   		 	col.a = s.Alpha;
    		return col;
		}
		sampler2D _MainTex;
		sampler2D _Bump;
		float _Snow;
		float4 _SnowColor;
		float4 _SnowDirection;    
		float _SnowDepth;

		struct Input {
    		float2 uv_MainTex;
    		float2 uv_Bump;
    		float3 worldNormal; INTERNAL_DATA
		};

		half _Glossiness;
		half _Metallic;
		fixed4 _Color;


		void surf (Input IN, inout SurfaceOutput o) {
    		half4 c = tex2D (_MainTex, IN.uv_MainTex);
    		o.Normal = UnpackNormal(tex2D(_Bump, IN.uv_Bump));

    		if (dot(WorldNormalVector(IN, o.Normal), _SnowDirection.xyz) > lerp(1,-1,_Snow)) {
        		o.Albedo = _SnowColor.rgb;
    		} else {
        		o.Albedo = c.rgb;
    		}
    		//o.Emission = c.rgb;	//自发光效果颜色
   			o.Alpha = c.a;
   			//o.Alpha = 1;
		}
		void vert (inout appdata_full v) {
			//_Object2World是将模型坐标系转换成时间坐标系的矩阵
			//transpose是转置，转置是因为，模型坐标系是右手坐标系，世界坐标系是左手坐标系
    		float4 sn = mul(transpose(_Object2World) , _SnowDirection);	//积雪应该用世界坐标
    		//float4 sn =_SnowDirection;	//本地坐标
    		if(dot(v.normal, sn.xyz) >= lerp(1,-1, (_Snow * 2) / 3)) {
        		v.vertex.xyz += (sn.xyz + v.normal) * _SnowDepth * _Snow;
    		}
		}
		ENDCG
	}
	FallBack "Diffuse"
}
